<template>
    <div class="main-box">
        <div style="width: 20%;margin:20px 0px">
            <div class="qualification-group">
                <li v-for="item in qualifications" :key="item.key"
                    :class=" qualification && qualification.key==item.key? 'qualificationActive' : ''"
                    @click="onChangeQualifications(item)">
                    <a-icon type="file-text" />
                    {{item.content}}
                </li>
            </div>
        </div>
        <div style="text-align: left;width: 20%;margin:20px 0px">
            <a-tree class="draggable-tree" draggable :tree-data="treeData" @select="navigationClickEvent" />
        </div>
        <div>
            <div style="padding: 5px;display: flex;justify-content: end;">
                <a-button type="primary" @click="correlationEvent">
                    <a-icon type="link" />
                    关联定位{{currentPage}}
                </a-button>
            </div>
            <div id="pdfBox" ref="pdfBox">
            </div>
        </div>
        <div style="width: 20%;margin:20px;border: 1px solid #ccc;text-align: left;">
            <div style="margin: 10px;">
                <a-tag style="overflow: hidden;padding: 5px;" :color="qualification.key==item.key?'red':'blue'" closable  @close="cancelCorrelation(item.key)" @click="onCorrelation(item)"
                    v-for="item in pageMapingQualification.get(this.currentPage)" :key="item.key">
                    <a-icon type="file-text" /> {{ item.content }}
                </a-tag>
            </div>
        </div>
    </div>
</template>

<script>
//引入pdf
import pdfjsLib from 'pdfjs-dist/build/pdf'
import _ from 'lodash';
export default {
    data() {
        return {
            pdf: '',
            treeData:[],
            value: 1,
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },
            pdfBox:null,
            qualifications: [
                { key: '001', content: '具有独立承担民事责任能力',x: 0, y: 0 },
                { key: '002', content: '具有良好的商业信誉和健全的财务会计制度' ,x: 0, y: 0},
                { key: '003', content: '具有履行合同所必须的设备和专业技术能力' ,x: 0, y: 0},
                { key: '004', content: '有依法缴纳税收和社会保障资金的良好记录' ,x: 0, y: 0},
                { key: '005', content: '参与政府活动三年内' ,x: 0, y: 0},
                { key: '006', content: '法律、行政法规规定的其他条件' ,x: 0, y: 0},
                { key: '007', content: '落实政府采购政策满足的资格要求' ,x: 0, y: 0},
                { key: '008', content: '商务技术文件' ,x: 0, y: 0},
            ],
            qualification:null,
            renderTask:null,
            currentPage: 1,
            pageMapingQualification: new Map(),
            dragging:false,
            mouseXOrigin :0,
            mouseYOrigin : 0,
            pointImg: null,
            dragImgUrl : 'https://file.yuncaitong.cn/0f91e60a5f6e4c68a4d39bfc8db9de3f',
            dragSuccessImgUrl : 'https://file.yuncaitong.cn/28f5f093877d4f1285056011be41418d',
            offsetX: 0,
            offsetY: 0,
        }
    },
    computed:{
    },
    mounted() {
        this.pdfBox = this.$refs.pdfBox;
        this.loadPdf('123');
        this.pdfBox.addEventListener('scroll', this.updateVisibleItems);
        this.updateVisibleItems();
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll);
    },
    methods: {
        /*
            点击得分点 
         */
        onCorrelation(item){
            //定位到当前页面的锚点
            const dragImg = document.getElementById(this.currentPage + "-" + item.key)
             //取消上一个point图片拖拽事件
            this.removeDragEvent();
            this.addDragEvent(dragImg);
            this.qualification = item;

        },
        addDragEvent(dragImg) {
            this.pointImg = dragImg;
            // 添加事件监听器
            dragImg.addEventListener('dragstart', this.handleDragStart, false);
            dragImg.addEventListener('drag', this.handleDrag, false);
            dragImg.addEventListener('dragover', this.handleDragOver, false);
            dragImg.addEventListener('dragend', this.handleDragEnd, false);
            this.pointImg.src = this.dragImgUrl;
        },
        /* 移除拖动事件 */
        removeDragEvent(){
            if(this.pointImg){
                // 移除事件监听器
                this.pointImg.removeEventListener('dragstart', this.handleDragStart);
                this.pointImg.removeEventListener('drag', this.handleDrag);
                this.pointImg.removeEventListener('dragover', this.handleDragOver);
                this.pointImg.removeEventListener('dragend', this.handleDragEnd);
                this.pointImg.src = this.dragSuccessImgUrl;
            }
        },
        /* 
            取消关联
        */
        cancelCorrelation(key) {
            const array = this.pageMapingQualification.get(this.currentPage);
            const index = array.findIndex(item => item.key == key);
            array.splice(index, 1);
            //移出图片
            const img = document.getElementById(this.currentPage + "-" + key);
            img.parentNode.removeChild(img);
            this.$forceUpdate()
        },
        /* 
            关联资质
         */
        correlationEvent() {
            const qualification = this.qualification;
            if (!qualification) {
                alert('请先选择资质');
                return;
            }
            //取消上一个point图片拖拽事件
            this.removeDragEvent();
            //定位获取当前页point图片
            if (!this.pageMapingQualification.get(this.currentPage)) {
                this.pageMapingQualification.set(this.currentPage, [qualification]);
                this.initCorrelation(this.currentPage,qualification.key,0,0);
            } else {
                const array = this.pageMapingQualification.get(this.currentPage);
                let tag = true;
                array.forEach(item => {
                    if (item.key == qualification.key) {
                        tag = false;
                        return;
                    }
                });
                if (tag) {
                    array.push(qualification);
                    this.initCorrelation(this.currentPage,qualification.key,0,0);
                } else {
                    this.initCorrelation(this.currentPage,qualification.key,qualification.x,qualification.y);
                    alert('该页已关联过该资质');
                }
            }
            this.$forceUpdate()
        },
        /* 初始化定位图片 */
        initCorrelation(currentPage,key,x,y) {
            const dragImg = document.getElementById(currentPage + "-" + key);
            if (dragImg) {
                this.addDragEvent(dragImg);
                return
            }
            //创建图片
            const img = document.createElement("img");
            img.src = this.dragImgUrl;
            img.style.position = "absolute";
            img.style.left = x + 'px';
            img.style.top = y + 'px';
            img.style.width = '75px';
            img.id = currentPage + "-" + key;
            img.draggable = true; // 设置元素为可拖动
            this.pointImg = img;
            // 添加事件监听器
            this.addDragEvent(img);
            //添加到页面
            document.getElementById('pdf-' + currentPage).appendChild(img);
        },
        //添加拖动开始事件
        handleDragStart(event) {
            event.dataTransfer.setData('text/plain', ''); // 防止默认行为
            this.dragging = true;
            this.mouseXOrigin = event.clientX;
            this.mouseYOrigin = event.clientY;
            this.offsetX = parseInt(event.target.style.left) || 0;
            this.offsetY = parseInt(event.target.style.top) || 0;
        },
        //添加拖动中事件
        handleDrag(event) {
            if (this.dragging) {
                const dx = event.clientX - this.mouseXOrigin;
                const dy = event.clientY - this.mouseYOrigin;
                this.offsetX += dx;
                this.offsetY += dy;
                this.mouseXOrigin = event.clientX;
                this.mouseYOrigin = event.clientY;
                const parentCanvas = this.pointImg.parentNode
                if ((this.offsetX > 0 && this.offsetX < parentCanvas.offsetWidth - 75) && (this.offsetY > 0 && this.offsetY < parentCanvas.offsetHeight - 75)) {
                    this.pointImg.style.left = this.offsetX + 'px'
                    this.pointImg.style.top = this.offsetY + 'px'

                } else {
                    event.preventDefault()
                }
            }
        },
        handleDragOver(event) {
            event.preventDefault();
        },

        //添加拖动结束事件
        handleDragEnd(event) {
            event.preventDefault()
            if (this.dragging) {
                const dx = event.clientX - this.mouseXOrigin;
                const dy = event.clientY - this.mouseYOrigin;
                this.offsetX += dx;
                this.offsetY += dy;
                this.mouseXOrigin = event.clientX;
                this.mouseYOrigin = event.clientY;

                const parentCanvas = this.imgEle.parentNode
                if ((this.offsetX > 0 && this.offsetX < parentCanvas.offsetWidth - 75) && (this.offsetY > 0 && this.offsetY < parentCanvas.offsetHeight - 75)) {
                    this.imgEle.style.left = this.offsetX + 'px'
                    this.imgEle.style.top = this.offsetY + 'px'
                    this.qualification.x = offsetX;
                    this.qualification.y = offsetY;
                } else {
                    event.preventDefault()
                }
            }
            this.dragging = false;
        },
        /* 
            pdf页面滑动事件
        */
        updateVisibleItems:_.debounce(function() {
            const pdfBox = document.getElementById('pdfBox');
            const canvasBoxs = pdfBox.getElementsByClassName('canvasBox');
             for (let index = 0; index < canvasBoxs.length; index++) { 
                const item = canvasBoxs[index];
                const rect = item.getBoundingClientRect();
                const top = rect.top;
                const bottom = rect.bottom;
                 if (-600 <= top && top <= 200 && bottom >= 100) {
                    this.renderPageRange(Number(item.getAttribute('id').split('-')[1]),this.pages, this,'type');
                    break;
                 }
             } 
        },100),
        /* 
            资质选择
        */
        onChangeQualifications(qualification){
            this.qualification = qualification;
            this.removeDragEvent();
        },
        /*
         递归生成树形结构
         */
        recursionTree(items){
            if (items && items.length > 0) {
                items.forEach(item => {
                    if (item.items && item.items.length > 0) {
                        this.recursionTree(item.items);
                        item.children = item.items;
                    }
                });
            }
        },
        /**
         * 加载pdf
         */
        loadPdf(type) {
            document.getElementById("pdfBox").innerHTML = ""
            const date = new Date().getTime()
             const url = '../../static/pdf/bookmark.pdf'
           //const url = 'http://speedcn.vicp.cc:1380/provider/tsinghua.war/tsinghua.api/publish/2018/12/28/19298725E9B22CB760B2D828C9FBA207/content.pdf'
            // const url = `//file.yct.ink/c17d7cfe4de24ed2ab5b46c38a5d5c6c?date=${date}`;
            pdfjsLib.getDocument(url, { 'Cache-Control': 'max-age=0' }).promise.then(async (pdf) => {
                console.log(pdf);
                this.pdf = pdf;
                let pages = pdf.numPages;
                this.pages = pages;
                // 获取 PDF 的书签（导航）
                const outline = await pdf.getOutline();
                this.recursionTree(outline);
                this.treeData = outline;
                const _this = this;
                //创建对应页数的div
                this.renderPageDiv(pages);
                //渲染pdf
                 this.renderPageRange(1, pages, _this, type);
            })
        },
        /* 
            渲染承载pdf的div
        */
        renderPageDiv(pages){
           for (let i = 1; i <= pages; i++) {
               const canvasBox = document.createElement("div")
               canvasBox.setAttribute("id", "pdf-" + i);
               canvasBox.classList.add('canvasBox')
               const pdfBox = document.getElementById('pdfBox')
               pdfBox.appendChild(canvasBox);
           }
       },

        /* 
           点击导航跳转页面
        */
         navigateToPage(item) {
            this.pdf.getPageIndex({ 'gen': item.dest[0].gen, 'num': item.dest[0].num }).then(async(pageNumber) => {
               await this.renderPageRange(pageNumber + 1, this.pages, this, "index");
                //拿到pdf的div容器
                const pageElement = document.getElementById(`pdf-${pageNumber + 1}`);
                // 滚动页面
                if (pageElement) {
                    requestAnimationFrame(() => {
                       pageElement.scrollIntoView();
                    });
                }
            });
        },
          /* 
            书签点击事件        
        */
        navigationClickEvent(selectedKeys,e,selectedNodes,node,event) {
            this.navigateToPage(e.selectedNodes[0].componentOptions.propsData.dataRef);
        },
        /**
          * 渲染pdf
          */
       async renderPageRange(pageNumber, pageAllCounts, _this, type) {
            this.currentPage = pageNumber;
            //拿到pdf的div容器
            const pageElement = document.getElementById(`pdf-${pageNumber}`);
            //查看是否有pdf内容
            if (pageElement && !pageElement.hasChildNodes()) {
                this.renderPage(pageNumber, pageAllCounts, _this, type);
            }
            //渲染前后两页
            const prePageElement = document.getElementById(`pdf-${pageNumber - 1}`);
            const backPageElement = document.getElementById(`pdf-${pageNumber + 1}`);
            if (prePageElement && !prePageElement.hasChildNodes()) {
                this.renderPage(pageNumber - 1, this.pages, this, "pre");
            }
            if (backPageElement && !backPageElement.hasChildNodes()) {
                this.renderPage(pageNumber + 1, this.pages, this, "back");
            }
        },
      async renderPage(pageNumber, pageAllCounts, _this, type) {
        this.pdf.getPage(pageNumber).then((page) => {
            console.log(page);
                const viewport = page.getViewport(1);
                // 创建canvas承载pdf内容
                const canvas = document.createElement("canvas")
                const canvasContext = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                canvas.style.display = "block"

                const canvasBox = document.getElementById(`pdf-${pageNumber}`)
                canvasBox.style.height = viewport.height + 'px'
                canvasBox.style.width = viewport.width + 'px'
                canvasBox.style.position = "relative"
                canvasBox.style.marginBottom = "10px"
                canvasBox.appendChild(canvas)

                const renderContext = {
                    canvasContext,
                    viewport
                };
                const renderTask = page.render(renderContext);
            });
        },
    },

}
</script>

<style>
#pdfBox {
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 842px;
}
.main-box {
  display: flex;
  justify-content: start;
  position: relative;
  background: #F5F5F5;
  height: 100%;
}
.canvasBox{
}
#pdf-outline {
    border: 1px solid #ccc;
}
#pdf-outline li {
    list-style: none;
    padding: 5px;
}
#pdf-outline li a {
    text-decoration: none;
    color: black;
}
.qualification-group{
    display: flex;
    flex-direction: column;
    align-items: left;
    list-style: none;
    max-width: 100%;
    overflow: hidden;
    border-right: 1px dashed #ccc;
    border-left: 1px dashed #ccc;
    height: 100%;
    height: 100vh;
    margin-left: 10px;
}
.qualification-group li{
    padding: 5px;
    text-align: left;
    padding-left: 15px;
    transition: background 0.3s ease, color 0.3s ease, font-weight 0.3s ease;
}
.qualification-group li:hover{
    background: #EBF5FE;
    cursor: pointer;
    color: #2872D1;
}
.qualificationActive{
    background: #EBF5FE;
    cursor: pointer;
    color: #2872D1;
    font-weight: bolder;
}


</style>